package cn.virens.common.easyexcel.dict;

import cn.idev.excel.converters.Converter;
import cn.idev.excel.write.handler.WriteHandler;
import cn.virens.common.util.exception.APIException;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@SuppressWarnings("serial")
public class ExcelDictStack implements Serializable {
    private static final ThreadLocal<ExcelDictStack> LOCAL = new InheritableThreadLocal<>();

    private static final ExcelDict EMPTY_DICT = new ExcelDict(Collections.emptyList());

    private final Map<Class<?>, ExcelDict> map = new ConcurrentHashMap<>();

    /**
     * 新建EXCEL字典库
     */
    public static ExcelDictStack registerDictStack() throws APIException {
        ExcelDictStack stack = new ExcelDictStack();

        LOCAL.set(stack);

        return stack;
    }

    /**
     * 获取字典
     */
    public static ExcelDict getDict(Class<?> clazz) throws APIException {
        ExcelDict res = LOCAL.get().get(clazz);
        if (res == null || clazz == null) {
            return EMPTY_DICT;
        }

        return res;
    }

    /**
     * 获取写入处理列表
     */
    public List<WriteHandler> getWriteHandlerList() throws APIException {
        return map.values().stream().map(dictItem -> {
            return dictItem.getConverter();
        }).collect(Collectors.toList());
    }

    /**
     * 获取转换器列表
     */
    public List<Converter<?>> getConverterList() throws APIException {
        return map.values().stream().map(dictItem -> {
            return dictItem.getConverter();
        }).collect(Collectors.toList());
    }

    /**
     * 注册字典
     */
    public <T> void putDict(ExcelDict dict) throws APIException {
        this.map.put(dict.getConverterClass(), dict);
    }

    /**
     * 获取字典
     */
    private ExcelDict get(Class<?> clazz) {
        return map.get(clazz);
    }
}
